from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
from datetime import datetime
from sqlalchemy.orm import Session
from backend.database import SessionLocal
from backend.models import Device, ScheduleLog
from backend.backup_service import BackupService
import logging

logger = logging.getLogger(__name__)

class BackupScheduler:
    """备份任务调度器"""
    
    def __init__(self):
        self.scheduler = BackgroundScheduler()
        self.scheduler.start()
        self.current_interval = 24  # 默认24小时
    
    def auto_backup_all_devices(self):
        """自动备份所有启用自动备份的设备"""
        db = SessionLocal()
        log = ScheduleLog(
            job_name="自动备份所有设备",
            status="running"
        )
        db.add(log)
        db.commit()
        
        try:
            # 获取所有启用自动备份的活动设备
            devices = db.query(Device).filter(
                Device.is_active == True,
                Device.auto_backup == True
            ).all()
            
            log.devices_count = len(devices)
            success_count = 0
            failed_count = 0
            
            backup_service = BackupService(db)
            
            for device in devices:
                try:
                    backup_service.backup_device(device.id, is_manual=False)
                    success_count += 1
                    logger.info(f"设备 {device.name} 备份成功")
                except Exception as e:
                    failed_count += 1
                    logger.error(f"设备 {device.name} 备份失败: {str(e)}")
            
            log.success_count = success_count
            log.failed_count = failed_count
            log.status = "completed"
            log.message = f"备份完成：成功 {success_count}，失败 {failed_count}"
            
        except Exception as e:
            log.status = "failed"
            log.message = f"调度任务失败: {str(e)}"
            logger.error(f"自动备份任务失败: {str(e)}")
        
        finally:
            log.execute_time = datetime.utcnow()
            db.commit()
            db.close()
    
    def start_auto_backup_job(self, hours: int = 24):
        """启动自动备份定时任务"""
        self.current_interval = hours
        # 每N小时执行一次
        self.scheduler.add_job(
            func=self.auto_backup_all_devices,
            trigger=IntervalTrigger(hours=hours),
            id='auto_backup_job',
            name='自动备份所有设备',
            replace_existing=True
        )
        logger.info(f"自动备份任务已启动，间隔: {hours} 小时")
    
    def restart_backup_job(self, hours: int):
        """重启备份任务（更新间隔时间）"""
        self.current_interval = hours
        try:
            # 移除旧任务
            self.scheduler.remove_job('auto_backup_job')
        except:
            pass
        
        # 添加新任务
        self.start_auto_backup_job(hours)
        logger.info(f"备份任务已重启，新间隔: {hours} 小时")
    
    def get_current_interval(self):
        """获取当前备份间隔"""
        return self.current_interval
    
    def stop(self):
        """停止调度器"""
        self.scheduler.shutdown()

# 全局调度器实例
backup_scheduler = BackupScheduler()
